<?php

namespace app\rongcui\controller;

use app\department\model\DepartmentModel;
use app\department\model\UserModel;
use app\rongcui\model\CustomerNatureModel;
use app\rongcui\model\RongcuiBuyerModel;
use app\rongcui\model\RongcuiBuyerUserModel;
use app\rongcui\model\RongcuiFollowModel;
use app\rongcui\model\RongcuiPotentialCustomerModel;
use cmf\controller\AdminBaseController;
use tree\Tree;

class DataController extends AdminBaseController
{
    public function develop() {
        $where = [
            'role_item.config_id' => 1,
            'role_item.item_id' => 2,
            'user.user_status' => ['neq',0]
        ];
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['user.user_nickname'] = ['like', "%$keyword%"];
        }

//        $time = [
//            'starttime' => strtotime(date('Y-m-d')),
//        ];
//        $time['endtime'] = $time['starttime'] + 86399;
//        if (input('start_time')) {
//            $time['starttime'] = strtotime(input('start_time'));
//        }
//        if (input('end_time')) {
//            $time['endtime'] = strtotime(input('end_time')) + 86499;
//        }
        $admin_id = cmf_get_current_admin_id();
        $depwhere = [];
        $dep_all = getGroups(5);
        if($admin_id != 1) {
            $userGroup = getUsersGroup($admin_id);
            $depwhere['id'] = ['in',array_intersect(explode(',',$dep_all),explode(',',$userGroup))];
            $where['dep_id'] = ['in',array_intersect(explode(',',$dep_all),explode(',',$userGroup))];
        }else{
            $depwhere['id'] = ['in',$dep_all];
        }
        $dep_id= $this->request->param('dep_id', 0, 'intval');
        if($dep_id) {
            $where['dep_id'] = ['in',getGroups($dep_id)];
        }
        $departmentModel = new DepartmentModel();
        $deps = $departmentModel->where($depwhere)->select()->toArray();
        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $parent_id = 99999;
        foreach ($deps as $key => $value) {
            $deps[$key]['selected'] = ($dep_id == $value['id']) ? 'selected' : '';
            if($value['parent_id'] < $parent_id) $parent_id = $value['parent_id'];
        }
        $tree->init($deps);
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $deps = $tree->getTree($parent_id, $str);
        $this->assign("deps", $deps);

        $time = strtotime(date('Y-m-d'));

        $rongcuiFollowModel = new RongcuiFollowModel();
        $dataFollow = $rongcuiFollowModel
            ->where([
                'type'=>3,
//                'create_time' => ['between', [$time['starttime'], $time['endtime']]]
            ])
            ->field([
                'uid,count(id) fcount',
                "count(create_time >= {$time} or null) fcount_day"
            ])
            ->group('uid')
            ->buildSql();

        $customerNatureModel = new CustomerNatureModel();
        $natures = $customerNatureModel
            ->where(['type' => 9])
            ->select();

        $field = [
            'uid'
        ];
        foreach ($natures as $nature) {
            $field[] ="count(potential_customer.attorn = {$nature['id']} or null) ncount_{$nature['id']}";
            $field[] ="count(potential_customer.attorn = {$nature['id']} and potential_customer.create_time >= {$time} or null) ncount_day_{$nature['id']}";
        }
        $rongcuiPotentialCustomerModel = new RongcuiPotentialCustomerModel();
        $dataNatrue = $rongcuiPotentialCustomerModel
            ->alias('potential_customer')
            ->join('__CUSTOMER_NATURE__ nature','potential_customer.attorn = nature.id')
            ->field($field)
            ->group('uid')
            ->buildSql();

        $userModel = new UserModel();
        $lists = $userModel
            ->alias('user')
            ->join('__ROLE_USER__ role_user', 'user.id = role_user.user_id')
            ->join('__ROLE_ITEM__ role_item', 'role_item.role_id = role_user.role_id and config_id = 1')
            ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
            ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
            ->join($dataFollow . ' follow','user.id = follow.uid','left')
            ->join($dataNatrue . ' natrue','user.id = natrue.uid','left')
            ->where($where)
            ->field([
                'user.user_nickname,dep.name as depname,user.id',
                'follow.*',
                'natrue.*'
            ])
            ->select();

        $this->assign('lists', $lists);
        $this->assign('natures', $natures);
        return $this->fetch();
    }

    public function market() {
        $where = [
            'role_item.config_id' => 1,
            'role_item.item_id' => 3,
            'user.user_status' => ['neq',0]
        ];
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['user.user_nickname'] = ['like', "%$keyword%"];
        }

//        $time = [
//            'starttime' => strtotime(date('Y-m-d')),
//        ];
//        $time['endtime'] = $time['starttime'] + 86399;
//        if (input('start_time')) {
//            $time['starttime'] = strtotime(input('start_time'));
//        }
//        if (input('end_time')) {
//            $time['endtime'] = strtotime(input('end_time')) + 86499;
//        }
        $admin_id = cmf_get_current_admin_id();
        $depwhere = [];
        $dep_all = getGroups(5);
        if($admin_id != 1) {
            $userGroup = getUsersGroup($admin_id);
            $depwhere['id'] = ['in',array_intersect(explode(',',$dep_all),explode(',',$userGroup))];
            $where['dep_id'] = ['in',array_intersect(explode(',',$dep_all),explode(',',$userGroup))];
        }else{
            $depwhere['id'] = ['in',$dep_all];
        }
        $dep_id= $this->request->param('dep_id', 0, 'intval');
        if($dep_id) {
            $where['dep_id'] = ['in',getGroups($dep_id)];
        }
        $departmentModel = new DepartmentModel();
        $deps = $departmentModel->where($depwhere)->select()->toArray();
        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $parent_id = 99999;
        foreach ($deps as $key => $value) {
            $deps[$key]['selected'] = ($dep_id == $value['id']) ? 'selected' : '';
            if($value['parent_id'] < $parent_id) $parent_id = $value['parent_id'];
        }
        $tree->init($deps);
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $deps = $tree->getTree($parent_id, $str);
        $this->assign("deps", $deps);


        $time = strtotime(date('Y-m-d'));
        $rongcuiFollowModel = new RongcuiFollowModel();
        $dataFollow = $rongcuiFollowModel
            ->where([
                'type'=>2,
//                'create_time' => ['between', [$time['starttime'], $time['endtime']]]
            ])
            ->field([
                'uid,count(id) fcount',
                "count(create_time >= {$time} or null) fcount_day"
            ])
            ->group('uid')
            ->buildSql();

        $customerNatureModel = new CustomerNatureModel();
        $natures = $customerNatureModel
            ->where(['type' => 8])
            ->select();

        $field = [
            'uid'
        ];
        foreach ($natures as $nature) {
            $field[] ="count(buyer.nature = {$nature['id']} or null) ncount_{$nature['id']}";
            $field[] ="count(buyer.nature = {$nature['id']} and buyer.create_time >= {$time} or null) ncount_day_{$nature['id']}";
        }
        $rongcuiBuyerModel = new RongcuiBuyerModel();
        $dataNatrue = $rongcuiBuyerModel
            ->alias('buyer')
            ->join('__CUSTOMER_NATURE__ nature','buyer.nature = nature.id')
            ->join('__RONGCUI_BUYER_USER__ buser','buser.pid = buyer.id and buser.level = 1')
            ->field($field)
            ->group('uid')
            ->buildSql();

        $userModel = new UserModel();
        $lists = $userModel
            ->alias('user')
            ->join('__ROLE_USER__ role_user', 'user.id = role_user.user_id')
            ->join('__ROLE_ITEM__ role_item', 'role_item.role_id = role_user.role_id and config_id = 1')
            ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
            ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
            ->join($dataFollow . ' follow','user.id = follow.uid','left')
            ->join($dataNatrue . ' natrue','user.id = natrue.uid','left')
            ->where($where)
            ->field([
                'user.user_nickname,dep.name as depname,user.id',
                'follow.*',
                'natrue.*'
            ])
            ->select();

        $this->assign('lists', $lists);
        $this->assign('natures', $natures);
        return $this->fetch();
    }

    public function data() {
        $data = [];
        $rongcuiBuyerModel = new RongcuiBuyerModel();
        $buyerData = $rongcuiBuyerModel
            ->alias('buyer')
            ->join('__CUSTOMER_NATURE__ nature','nature.id = buyer.nature and nature.type = 8','left')
            ->field('nature,nature.name,count(buyer.id) count')
            ->group('buyer.nature')
            ->select()->toArray();

        $rongcuiPotentialCustomerModel = new RongcuiPotentialCustomerModel();
        $customerData = $rongcuiPotentialCustomerModel
            ->alias('customer')
            ->join('__CUSTOMER_NATURE__ nature','nature.id = customer.attorn and nature.type = 9','left')
            ->field('attorn nature,nature.name,count(customer.id) count')
            ->group('customer.attorn')
            ->select()->toArray();

        foreach ($buyerData as $key => $value) {
            if($value['nature'] == 0) {
                $buyerData[$key]['name'] = '其他';
            }
        }
        $data['buyer'] = [
            'title' => '客户性质统计表',
            'name' => '客户性质',
            'data' => $buyerData
        ];
        foreach ($customerData as $key => $value) {
            if($value['nature'] == 0) {
                $customerData[$key]['name'] = '其他';
            }
        }
        $data['customer'] = [
            'title' => '产品转让统计表',
            'name' => '产品转让',
            'data' => $customerData
        ];

        $this->assign('data',$data);
        return $this->fetch();
    }

    function detail() {
        $type = $this->request->param('detail','');
        switch ($type) {
            case 'buyer':
                $rongcuiBuyerModel = new RongcuiBuyerModel();
                $buyerData = $rongcuiBuyerModel
                    ->alias('buyer')
                    ->field('nature,nature.name,count(buyer.id) count')
                    ->group('buyer.nature')
                    ->select()->toArray();
                break;
        }
    }
}